﻿#include "UDP_Mode.h"
#include <QDebug>

#define DEBUGinfo qDebug()

UDP_Service::UDP_Service()
{
    UdpServer = new QUdpSocket(this);
    connect(UdpServer,&QUdpSocket::readyRead,this,&UDP_Service::ReadUdpMessage);
}

UDP_Service::~UDP_Service()
{
    if(UdpServer->isOpen())
    {
        UdpServer->close();
    }
}

void UDP_Service::OpenUdp(QString ipAddress, quint16 port)
{
    if(UdpServer->bind(QHostAddress(ipAddress),port))//绑定本地端口
    {
        emit BindSuccess();
        DEBUGinfo<<"bind success";
    }
    else
    {
        DEBUGinfo<<"bind fail";
    }
}

void UDP_Service::CloseUdp()
{
    UdpServer->close();
}
//发送消息
void UDP_Service::SendUdpMsg(QByteArray msg,QString obj_ip,quint16 obj_port)
{
    UdpServer->writeDatagram(msg,msg.size(),QHostAddress(obj_ip),obj_port);
}
//接收消息
void UDP_Service::ReadUdpMessage()
{
    while(UdpServer->hasPendingDatagrams())
    {
        QNetworkDatagram datagram = UdpServer->receiveDatagram();
        qDebug()<<"udp message.";
        emit UdpModeMsg(datagram.data());
    }
    //收到的消息
//    QByteArray Recive_UDPmsg;
//    Recive_UDPmsg.resize(UdpServer->pendingDatagramSize());
//    UdpServer->readDatagram(Recive_UDPmsg.data(),Recive_UDPmsg.size(),&from_address,&from_port);
//    emit UdpModeMsg(Recive_UDPmsg);
}
